package com.yf.modules.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yf.Utils.CacheKey;
import com.yf.Utils.FileUtil;
import com.yf.Utils.RedisUtils;
import com.yf.dao.DictDetailMapper;
import com.yf.dao.DictMapper;
import com.yf.domain.dict.Dict;
import com.yf.domain.dict.DictDetail;
import com.yf.model.query.DictQueryCriteria;
import com.yf.modules.system.service.api.DictService;
import com.yf.response.exceptions.BusinessException;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;

/**
 * @author chentianwei
 * @date 2024-10-14 14:00
 * @description 字典Api实现层
 */
@Service
@Slf4j
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    private final DictMapper dictMapper;
    private final DictDetailMapper dictDetailMapper;
    private final RedisUtils redisUtils;

    public DictServiceImpl(DictMapper dictMapper,
                           DictDetailMapper dictDetailMapper,
                           RedisUtils redisUtils) {
        this.dictMapper = dictMapper;
        this.dictDetailMapper = dictDetailMapper;
        this.redisUtils = redisUtils;
    }

    /**
     * 查询全部字典
     *
     * @param criteria 查询条件
     * @return 字典数据
     */
    @Override
    public List<Dict> queryDict(DictQueryCriteria criteria) {
        return dictMapper.findAll(criteria);
    }

    /**
     * 创建新字典
     *
     * @param dict 字典Key
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Dict dict) {
        if (dict.getId() != null) {
            throw new BusinessException("此字典已存在，无法再创建");
        }
        save(dict);
    }

    /**
     * 更新字典
     *
     * @param dict 字典key
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(Dict dict) {
        // 清理缓存
        delCaches(dict);
        Dict resource = getById(dict.getId());
        resource.setName(dict.getName());
        resource.setDescription(dict.getDescription());
        saveOrUpdate(resource);
    }

    /**
     * 删除字典
     *
     * @param ids 主键
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Set<Long> ids) {
        // 清理缓存
        List<Dict> dicts = dictMapper.selectBatchIds(ids);
        for (Dict dict : dicts) {
            delCaches(dict);
        }
        // 删除字典
        dictMapper.deleteByIds(ids);
        // 删除字典详情
        dictDetailMapper.deleteByDictBatchIds(ids);
    }

    /**
     * 下载字典合计
     *
     * @param response 返回流
     */
    @Override
    public void download(HttpServletResponse response) throws IOException {
        List<Dict> dictList = dictMapper.findAll(new DictQueryCriteria());
        List<Map<String, Object>> list = new ArrayList<>();
        for (Dict dict : dictList) {
            if(CollectionUtil.isNotEmpty(dict.getDictDetail())){
                for (DictDetail dictDetail : dict.getDictDetail()) {
                    Map<String,Object> map = new LinkedHashMap<>();
                    map.put("字典名称", dict.getName());
                    map.put("字典描述", dict.getDescription());
                    map.put("字典标签", dictDetail.getLabel());
                    map.put("字典值", dictDetail.getValue());
                    list.add(map);
                }
            } else {
                Map<String,Object> map = new LinkedHashMap<>();
                map.put("字典名称", dict.getName());
                map.put("字典描述", dict.getDescription());
                map.put("字典标签", null);
                map.put("字典值", null);
                list.add(map);
            }
        }
        FileUtil.downloadExcel(list, response);

    }

    public void delCaches(Dict dict) {
        redisUtils.del(CacheKey.DICT_NAME + dict.getName());
    }
}
